<template>
  <div class="student-list-container" style="width: 100% !important; margin: 0 !important; padding: 0 !important; position: absolute; top: 0; left: 0; right: 0; bottom: 0;">
    <!-- 管理员控制台头部 -->
    <el-header class="admin-header">
      <div class="header-left">
        <h1>在线考试系统管理控制台</h1>
      </div>
      <div class="header-right">
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-icon><UserFilled /></el-icon>
            <span class="username">{{ userInfo.username }}</span>
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleChangePassword">修改密码</el-dropdown-item>
              <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>
    
    <el-card class="student-card" style="border-radius: 0;">
      <template #header>
        <div class="card-header">
          <h2>学生管理</h2>
          <!-- 移除添加按钮，添加功能由用户管理模块负责 -->
        </div>
      </template>
      <div class="search-bar" style="padding: 10px 10px 20px 10px !important; margin: 0 !important;">
        <el-input v-model="searchQuery" placeholder="请输入学生姓名或学号" prefix-icon="Search"
          style="width: 300px; margin-right: 10px;" />
        <el-select v-model="classFilter" placeholder="选择班级" style="width: 200px; margin-right: 10px;">
          <el-option label="全部班级" value=""></el-option>
          <el-option label="计算机一班" value="1"></el-option>
          <el-option label="计算机二班" value="2"></el-option>
          <el-option label="数学一班" value="3"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
      <!-- 添加表格包装器以支持水平滚动 -->
      <div class="table-wrapper">
        <el-table v-loading="loading" :data="filteredStudents" style="width: 100%">
          <el-table-column prop="studentId" label="学生ID" width="80"></el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="realName" label="真实姓名" width="120"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80"></el-table-column>
          <el-table-column prop="studentNo" label="学号" width="120"></el-table-column>
          <el-table-column prop="className" label="班级" width="120"></el-table-column>
          <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
          <el-table-column prop="enrollmentDate" label="入学日期" width="120">
            <template #default="{ row }"> {{ formatDate(row.enrollmentDate) }}</template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }"> {{ formatDate(row.createTime) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEditStudent(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteStudent(row.studentId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination" style="padding: 20px 10px !important; margin: 0 !important; justify-content: flex-end;">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          :total="filteredStudentsTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    
    <!-- 编辑学生信息的对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="`编辑学生：${editForm.studentNo ?? ''}`"
        width="600px"
        center
      >
        <el-form :model="editForm" label-width="120px" class="edit-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学生ID" prop="studentId">
                <el-input v-model="editForm.studentId" disabled placeholder="学生ID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户ID" prop="userId">
                <el-input v-model="editForm.userId" disabled placeholder="用户ID" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学号" prop="studentNo">
                <el-input v-model="editForm.studentNo" placeholder="请输入学号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班级" prop="classId">
                <el-select
                  v-model="editForm.classId"
                  placeholder="请选择班级"
                  filterable
                  :filter-method="(query: string) => {
                    classSearchQuery = query
                  }"
                  remote
                  :remote-method="(query: string) => {
                    classSearchQuery = query
                  }"
                  :loading="false"
                >
                  <el-option
                    v-for="cls in classList"
                    :key="String(cls.value)"
                    :label="cls.label"
                    :value="cls.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入学日期" prop="enrollmentDate">
                <el-date-picker
                  v-model="editForm.enrollmentDate"
                  type="date"
                  placeholder="选择入学日期"
                  style="width: 100%;"
                  :picker-options="{
                    // 设置日期选择器为中文样式
                    firstDayOfWeek: 1,
                    format: 'YYYY-MM-DD',
                    shortcuts: [
                      { text: '今天', onClick(picker: any) { picker.$emit('pick', new Date()); }},
                      { text: '昨天', onClick(picker: any) { const date = new Date(); date.setTime(date.getTime() - 3600 * 1000 * 24); picker.$emit('pick', date); }},
                      { text: '一周前', onClick(picker: any) { const date = new Date(); date.setTime(date.getTime() - 3600 * 1000 * 24 * 7); picker.$emit('pick', date); }}
                    ]
                  }"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmEdit">确定</el-button>
          </span>
        </template>
      </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, postJson } from '../../utils/api'
import { UserFilled, ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()

const userInfo = ref({
  username: '',
  roleName: ''
})

onMounted(() => {
  // 从本地存储获取用户信息
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
})

const handleLogout = async () => {
  try {
    // 调用后端登出接口，带上cookie
    await get('/user/logout')
    
    // 清除本地存储的用户信息
    localStorage.removeItem('user')
    
    // 跳转到登录页面
    router.push('/login')
    
    ElMessage.success('退出登录成功')
  } catch (error) {
    console.error('退出登录失败:', error)
    // 即使后端调用失败，也要清除本地状态并跳转
    localStorage.removeItem('user')
    router.push('/login')
    ElMessage.success('退出登录成功')
  }
}

const handleChangePassword = () => {
  router.push('/admin/change-password')
}

// 学生数据
const students = ref<any[]>([])

// 加载状态
const loading = ref(false)

// 搜索条件
const searchQuery = ref('')
const classFilter = ref('')

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 编辑对话框显示状态
const dialogVisible = ref(false)

// 编辑表单数据（符合后端接口要求的字段）
const editForm = reactive({
  studentId: '',
  userId: '',
  classId: '',
  studentNo: '',
  enrollmentDate: ''
})

// 班级列表数据
const classList = ref<any[]>([])

// 班级搜索关键字
const classSearchQuery = ref<string>('')

// 监听对话框显示状态，当对话框打开时加载班级数据
watch(dialogVisible, (newVal) => {
  if (newVal) {
    loadClassList()
  }
})

// 过滤后的学生数据
const filteredStudents = computed<any[]>(() => {
  let result = students.value

  // 搜索过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      result = result.filter((student: any) =>
        student.realName?.toLowerCase().includes(query) ||
        student.studentNo?.toLowerCase().includes(query) ||
        student.username?.toLowerCase().includes(query)
      )
    }

  // 班级过滤
  if (classFilter.value) {
    result = result.filter((student: any) =>
      String(student.classId) === classFilter.value
    )
  }

  // 分页
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return result.slice(start, end)
})

// 过滤后的总条数
const filteredStudentsTotal = computed(() => {
  let result = students.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter((student: any) =>
      student.realName?.toLowerCase().includes(query) ||
      student.studentNo?.toLowerCase().includes(query) ||
      student.username?.toLowerCase().includes(query)
    )
  }

  // 班级过滤
  if (classFilter.value) {
    result = result.filter((student: any) =>
      String(student.classId) === classFilter.value
    )
  }

  return result.length
})

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 加载学生列表
const loadStudents = async () => {
  loading.value = true
  try {
    // 调用后端API获取学生列表
    const result = await get('/student/query')

    // 根据后端返回的数据格式处理
    if (result.code === 200) {
      // 假设后端返回的data字段是学生列表
      students.value = result.data || []
      // 更新分页总数
      pagination.total = result.dataCount || students.value.length
    } else {
      ElMessage.error(result.msg || '加载学生列表失败')
    }
  } catch (error) {
    console.error('加载学生列表失败:', error)
    ElMessage.error('网络错误，请检查后端服务是否正常运行')
  } finally {
    loading.value = false
  }
}

// 添加功能已移除，由用户管理模块负责

// 加载班级列表
const loadClassList = async () => {
  try {
    // 使用相对路径发送请求，避免URL重复拼接
    const result = await get('/class/query')
    
    if (result.code === 200 && result.data) {
      // 处理班级数据，将显示文本格式化为 grade+major+className
      classList.value = result.data.map((cls: any) => ({
        value: cls.classId,
        label: `${cls.grade || ''}${cls.major || ''}${cls.className || ''}`
      }))
    } else {
      ElMessage.error('获取班级列表失败')
    }
  } catch (error) {
    console.error('加载班级列表失败:', error)
    ElMessage.error('网络错误，请检查后端服务')
  }
}

// 编辑学生 - 打开编辑对话框
const handleEditStudent = async (row: any) => {
  try {
    // 调用后端API获取学生详情
    const result = await get(`/student/query/id?id=${row.studentId}`)

    if (result.code === 200) {
      // 填充编辑表单数据（只包含后端接受的字段）
      editForm.studentId = String(row.studentId)
      // 修复userId为0的问题：确保正确处理userId
      editForm.userId = row.userId !== undefined && row.userId !== null ? String(row.userId) : ''
      editForm.classId = row.classId ? String(row.classId) : ''
      editForm.studentNo = row.studentNo || ''
      editForm.enrollmentDate = row.enrollmentDate ? String(new Date(row.enrollmentDate).toISOString().split('T')[0]) : ''
      
      // 显示编辑对话框
      dialogVisible.value = true
    } else {
      ElMessage.error(result.msg || '获取学生详情失败')
    }
  } catch (error: any) {
    console.error('编辑学生失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 确认编辑 - 提交表单
const confirmEdit = async () => {
  try {
    // 准备更新数据，符合后端Student类结构要求
    const updatedData = {
      studentId: Number(editForm.studentId), // 转换为Integer类型
      userId: Number(editForm.userId),       // 转换为Integer类型
      classId: Number(editForm.classId),     // 转换为Integer类型
      studentNo: editForm.studentNo,         // 字符串类型
      enrollmentDate: editForm.enrollmentDate // LocalDate类型，格式为YYYY-MM-DD
    }
    
    // 调用后端API更新学生信息，使用POST方法并将数据作为JSON请求体发送
    const updateResult = await postJson('/student/update', updatedData)

    if (updateResult.code === 200) {
      ElMessage.success('更新成功')
      // 关闭对话框
      dialogVisible.value = false
      // 重新加载学生列表
      loadStudents()
    } else {
      ElMessage.error(updateResult.msg || '更新失败')
    }
  } catch (error: any) {
    console.error('提交编辑失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 删除学生
const handleDeleteStudent = async (studentId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该学生吗？此操作不可恢复。',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    loading.value = true
    // 调用后端API删除学生
    const result = await get(`/student/delete?id=${studentId}`)

    if (result.code === 200) {
      // 从本地数据中移除
      students.value = students.value.filter((student: any) => student.studentId !== studentId)
      ElMessage.success('学生删除成功')
      // 重新加载学生列表以确保数据一致性
      await loadStudents()
    } else {
      ElMessage.error(result.msg || '删除失败，请重试')
    }
  } catch (error: any) {
    // 用户取消删除或发生错误
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('操作失败，请检查网络连接或联系管理员')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1 // 重置到第一页
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
}

// 当前页码改变
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
}

// 页面加载时获取数据
onMounted(() => {
  loadStudents()
})
</script>

<style scoped>
.admin-header {
  background-color: #1890ff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left h1 {
  font-size: 20px;
  margin: 0;
  font-weight: normal;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: white;
}

.username {
  margin: 0 8px;
}

/* 重置样式并确保容器填满整个屏幕 */
:deep(.el-card) {
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  border-radius: 0;
  border: none;
  padding: 0 !important;
  /* 左贴合 */
}

/* 移除卡片头部和内容区域的默认内边距 */
:deep(.el-card__header) {
  padding: 0 !important;
  margin: 0 !important;
  border-bottom: none;
}

:deep(.el-card__body) {
  padding: 0 !important;
  margin: 0 !important;
  overflow: hidden;
}

/* 外层容器完全填充满屏幕 */
.student-list-container {
    padding: 0 !important;
    min-height: 100vh;
    height: 100vh;
    background-color: #f5f5f5;
    width: 100% !important;
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    overflow: hidden;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    border-radius: 0 !important;
  }

/* 卡片样式 - 完全消除内外边距和圆角 */
  .student-card {
    width: 100% !important;
    max-width: none !important;
    margin: 0 !important;
    padding: 0 !important;
    border: none !important;
    box-shadow: none !important;
    background-color: #fff;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    /* border-radius: 0 !important; */
  }

/* 头部样式 */
.card-header {
  padding: 10px 10px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 0;
  width: 100% !important;
}

.card-header h2 {
  margin: 0 !important;
  font-size: 18px;
  font-weight: bold;
  padding: 0 !important;
}

/* 搜索栏样式 */
.search-bar {
    padding: 10px 0 20px 0;
    background-color: #fff;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    min-width: 100%;
    width: 100%;
    margin: 0;
    /* 确保搜索栏最小宽度 */
  }

/* 表格容器样式 - 关键修改：添加水平滚动和最小宽度 */
.table-wrapper {
    flex: 1;
    overflow-x: auto;
    /* 允许水平滚动 */
    overflow-y: auto;
    /* 允许垂直滚动 */
    min-width: 100%;
    width: 100%;
    /* 确保表格有足够宽的最小宽度 */
    padding: 0;
    margin: 0;
  }

:deep(.el-table) {
    width: 100%;
    min-width: 100%;
    /* 确保表格有足够宽的最小宽度 */
  }

/* 强制表格列使用指定宽度 */
:deep(.el-table th) {
  white-space: nowrap;
  /* 防止表头文字换行 */
  font-size: 14px;
  /* 调整表头字体大小 */
  padding: 12px 8px;
  /* 调整表头内边距 */
}

:deep(.el-table td) {
  font-size: 13px;
  /* 调整表格内容字体大小 */
  padding: 12px 8px;
  /* 调整表格内容内边距 */
}

/* 分页样式 */
.pagination {
    padding: 20px 0;
    background-color: #fff;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    min-width: 100%;
    width: 100%;
    margin: 0;
    /* 确保分页栏最小宽度 */
  }

/* 编辑表单样式 */
.edit-form {
  padding: 10px 0;
}

.edit-form .el-form-item {
  margin-bottom: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    margin-top: 10px;
    width: 100%;
    flex-direction: column;
  }

  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-bar .el-input,
  .search-bar .el-select {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }

  .pagination {
    justify-content: center;
  }
  
  /* 编辑对话框的响应式调整 */
  .el-dialog {
    width: 90% !important;
    margin: 5vh auto !important;
  }
  
  .edit-form .el-col {
    --el-col-span: 24;
  }
}
</style>

/* 全局样式重置，确保整个页面背景一致 */
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
html {
  width: 100% !important;
  height: 100% !important;
  background-color: #f5f5f5 !important;
  overflow: hidden;
}

#app {
  width: 100% !important;
  height: 100% !important;
  background-color: #f5f5f5 !important;
}
</style>